<template>
  <div class="all-project">
    <div>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="自己的项目" @click="getFalse" v-if="isShow1">
          <!-- 新增项目 -->
          <a-button icon="plus" class="addProject" type="primary" @click="toProjectAdd">新增项目</a-button>
          <!-- 表格 -->
          <a-table
            rowKey="id"
            :columns="columns"
            :data-source="data"
            bordered
            :pagination="pagination"
          >
            <!-- 进度 -->
            <template slot="schedule">
              <a href>查看</a>
            </template>
            <template slot="status" slot-scope="text">
              <!-- 根据返回的数据进行判断审核状态 -->
              <span v-if="text == 92" style="color:blue;">审核成功</span>
              <span v-else-if="text == -1" style="color: #e6e6e6">审核失败</span>
              <span v-else-if="text == 1" style="color: black;">已保存</span>
              <span v-else style="color: red">审核中</span>
            </template>
            <template slot="action" slot-scope="text,record">
              <template>
                <a-button
                  type="primary"
                  size="small"
                  icon="cloud"
                  v-if="record.status===1||record.status === -1"
                  @click="submit(text,record)"
                >提交</a-button>
                <a-button
                  size="small"
                  icon="edit"
                  v-if="record.status === 1"
                  @click="editProject(text,record)"
                >修改</a-button>

                <a-popconfirm
                  v-if="record.status===0"
                  title="Are you sure delete this task?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteProject(text,record)"
                  @cancel="cancel"
                >
                  <a-button type="danger" icon="delete" size="small">删除</a-button>
                </a-popconfirm>
                <a-button
                  type="danger"
                  size="small"
                  icon="rollback"
                  v-if="record.status===1||record.status===-1"
                  @click="revokePorject(text,record)"
                >撤销</a-button>
              </template>
             
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="所有的项目" force-render @click="getTrue" v-if="isShow2">
          <a-table
            rowKey="id"
            :columns="columns1"
            :data-source="data1"
            bordered
            :pagination="pagination"
          >
            <!-- 进度 -->
            <template slot="schedule">
              <a href>查看</a>
            </template>
            <template slot="status" slot-scope="text">
              <!-- 根据返回的数据进行判断审核状态 -->
              <span v-if="text == 91" style="color:blue;">审核成功</span>
              <span v-if="text == 92" style="color:blue;">出函</span>
              <span v-else-if="text == -1" style="color: #e6e6e6">审核失败</span>
              <span v-else-if="text == 1" style="color: black">已保存</span>
              <!-- status是2、3、4都为审核状态 -->
              <span v-else style="color: red">审核中</span>
            </template>
            <template slot="action" slot-scope="text,record">
                <!-- 点击同意弹出对话框（model） 多文本输入框 -->
                <!-- 用isAble来控制同意和拒绝按钮的使用（组长同意后status变为3，则管理层同意/拒绝按钮禁用）
                使用了三元表达式
                -->
                <a-button
                  type="primary"
                  size="small"
                  icon="check"
                  :disabled="(auser.roleName=='超级管理员'||auser.roleName == 'SRM管理员'||auser.roleName == '项目部总经理')?(record.status > 3? true:false):false"
                  @click="agree(text,record)"
                >同意</a-button>
                <!--  @click="submit(text,record)" -->
                <a-modal v-model="isAgree" title="你确定同意此项目吗？" @ok="onCloseAgree">
                  <template>
                    <div>请输入原因</div>
                    <a-textarea v-model="agreeInput" placeholder="同意原因" :rows="4" />
                  </template>
                </a-modal>
                <!--  -->
                <a-button
                  type="danger"
                  size="small"
                  icon="close"
                  :disabled="(auser.roleName=='超级管理员'||auser.roleName == 'SRM管理员'||auser.roleName == '项目部总经理')?(record.status > 3? true:false):false"
                  @click="refuse(record)"
                >拒绝</a-button>
                <a-modal v-model="isRefuse" title="你确定不同意此项目吗？" @ok="refuseShowModal">
                  <template>
                    <div>请输入原因</div>
                    <a-textarea v-model="refuseInput" placeholder="拒绝原因" :rows="4" />
                  </template>
                </a-modal>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
    <a-modal v-model="visible" @ok="handleOk">
      <a-form>
        <a-form-item label="请选择下发的公司的名称">
          <a-select @change="companyChange" placeholder="请选择公司">
            <a-select-option
              v-for="(item,index) in companys"
              :key="index+'company'"
              :value="item.userId"
            >{{ item.username }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model="visible1" @ok="selectCompany">
      <a-form>
        <a-form-item label="请选择下发的公司的名称">
          <a-select @change="companyChange" placeholder="请选择公司">
            <a-select-option
              v-for="(item,index) in companys"
              :key="index+'company'"
              :value="item.userId"
            >{{item.username}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from "vuex";

const columns = [
  {
    title: "序号",
    width: 70,
    // 序号自增排列
    customRender: (text, record, index) => `${index + 1}`,
    key: "projectId",
    fixed: "left",
    align: "center",
  },
  {
    title: "项目名称",
    width: 150,
    dataIndex: "name",
    key: "name",
    fixed: "left",
    align: "center",
  },
  {
    title: "联系人",
    width: 150,
    dataIndex: "createUsername",
    key: "1",
    align: "center",
  },
  { title: "金额", dataIndex: "amount", key: "2", align: "center" },
  { title: "保函品种", dataIndex: "guaranteeKind", key: "3", align: "center" },
  { title: "保函类型", dataIndex: "guaranteeType", key: "4", align: "center" },
  // { title: "进度", dataIndex: "", key: "5", align: "center" },
  {
    title: "进度",
    dataIndex: "",
    key: "5",
    align: "center",
    scopedSlots: { customRender: "schedule" },
  },
  { title: "时间", dataIndex: "createTime", key: "6", align: "center" },
  // { title: "审核状态", dataIndex: "status", key: "7",align: 'center' },
  {
    title: "审核状态",
    dataIndex: "status",
    align: "center",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "Action",
    key: "operation",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
];

const columns1 = [
  {
    title: "序号",
    width: 70,
    // 序号自增排列
    customRender: (text, record, index) => `${index + 1}`,
    key: "projectId",
    fixed: "left",
    align: "center",
  },
  {
    title: "项目名称",
    width: 150,
    dataIndex: "name",
    key: "name",
    fixed: "left",
    align: "center",
  },
  {
    title: "联系人",
    width: 150,
    dataIndex: "createUsername",
    key: "1",
    align: "center",
  },
  { title: "金额", dataIndex: "amount", key: "2", align: "center" },
  { title: "保函品种", dataIndex: "guaranteeKind", key: "3", align: "center" },
  { title: "保函类型", dataIndex: "guaranteeType", key: "4", align: "center" },
  // { title: "进度", dataIndex: "", key: "5", align: "center" },
  {
    title: "进度",
    dataIndex: "",
    key: "5",
    align: "center",
    scopedSlots: { customRender: "schedule" },
  },
  { title: "时间", dataIndex: "createTime", key: "6", align: "center" },
  // { title: "审核状态", dataIndex: "status", key: "7",align: 'center' },
  {
    title: "审核状态",
    dataIndex: "status",
    align: "center",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "Action",
    key: "operation",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  data() {
    return {
      isture: false,
      isShow1: true,
      isShow2: true,
      data: [],
      columns,
      columns1,
      data1: [],
      visible: false,
      visible1: false,
      companyId: undefined,
      companys: [],
      agreeData: {}, // 点击同意后要提交数据库的数据
      refuseData: {}, // 点击拒绝后要提交数据库的数据
      isRefuse: false, // 拒绝的弹出框开关
      refuseInput: "", // 获取用户拒绝的原因
      isAgree: false, // 用户同意的弹出框开关
      agreeInput: "", // 用户统一的原因
      // 表格分页问题
      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "100"],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`,
      },
    };
  },
  // 请求数据
  async created() {
    // this.user = db.get("USER");
    // 获取用户id
    console.log("我是用户id", this.auser.userId);
    // 获取用户职位
    console.log("我是用户职位信息", this.auser.roleName);
    // 获取用户部门
    console.log("我是用户部门信息", this.auser.deptId);
    console.log("我是用户角色", this.roles[0]);
    // 获取用户权限
    this.getRole();
    // 获取自己的项目==传递的参数是个键值对
    this.$get("/project/list", {
      createUserId: this.auser.userId,
    }).then((res) => {
      console.log("获取到自己的项目", res.data.rows);
      // 注意data是个数组
      this.data = res.data.rows;
    });
    // 根据用户角色获取项目列表=====(是不是可以写个方法优化一个？？)
    if (this.roles[0] == "项目部分组组长") {
      // 获取部门的项目（一旦修改status的值，组长就获取不到组员的项目了）
      this.$get("/project/list", {
        deptId: this.auser.deptId,
        status: 2, //(status应该从数据库中获取)
      }).then((res) => {
        console.log("获取用户部门的项目列表", res.data.rows);
        this.data1 = res.data.rows;
        // 所有项目要筛选掉用户自己的
        for (var i = 0; i < this.data1.length; i++) {
          // 检测项目列表不能有自己的项目,撤销的，已保存的，审核失败的
          if (
            this.auser.userId == this.data1[i].createUserId ||
            this.data1[i].status == -1 ||
            this.data1[i].status == 0 ||
            this.data1[i].status == 1
          ) {
            this.data1.splice(i, 1);
            i--; //i需要自减，否则每次删除都会讲原数组索引发生变化
          }
        }
        console.log("筛选过后的data1", this.data1);
      });
    } else if (
      this.roles[0] == "项目部总经理" ||
      this.roles[0] == "超级管理员" ||
      this.roles[0] == "SRM管理员"
    ) {
      // 获取所有的项目
      this.$get("/project/list").then((res) => {
        console.log("获取所有的项目", res.data);
        this.data1 = res.data.rows;
        for (let i = 0; i < this.data1.length; i++) {
          // 所有项目要筛选掉用户自己的和审核失败的、撤销的、已保存的
          if (
            this.auser.userId == this.data1[i].createUserId ||
            this.data1[i].status == -1 ||
            this.data1[i].status == 0 ||
            this.data1[i].status == 1
          ) {
            this.data1.splice(i, 1);
            i--; //i需要自减，否则每次删除都会讲原数组索引发生变化
          }    
        }
        console.log("筛选过后的data1", this.data1);     
      });
    }

    // 获取第三方公司列表
    const companys = await this.$get("/common/company/list");
    console.log(companys);
    this.companys = companys.data.data;
  },
  // async created(){
  //   let res = await this.$get('/project/list')
  //   this.data1 = res.data.rows
  //   this.data = res.data.rows
  // },

  methods: {
    _getList() {
      this.$get("/project/list", {
        createUserId: this.auser.userId,
      }).then((res) => {
        console.log("获取到自己的项目", res.data.rows);
        this.data = res.data.rows;
      });
      this.$get("/project/list").then((res) => {
        console.log("2222", res.data.rows);
        this.data1 = res.data.rows;
      });
    },
    deleteProject(text, record) {
      const id = record.projectId;
      console.log(id);
      this.$delete(`/project/${id}`).then((res) => {
        if (res.data.code === "200") {
          this.$message.success("删除项目成功!");
          this._getList();
        }
      });
    },
    revokePorject(text, record) {
      let data = {
        status: 0,
        projectId: record.projectId,
        // amount: record.amount,
        // term: record.term,
        // rate: record.rate,
        // guaranteeKind: record.guaranteeKind,
        // guaranteeType: record.guaranteeType,
        // insideBasic: record.insideBasic,
        // insideLegal: record.insideLegal,
        // insideCounter: record.insideCounter,
      };
      this.$put("/project", data).then((res) => {
        if (res.data.code === "200") {
          this.$message.success("撤销项目成功,可以进行删除操作了");
          this._getList();
        }
      });
      console.log(data, "撤销项目需要提交的字段");
    },
    editProject(text, record) {
      console.log(record, "修改");
      this.$router.replace(`/project/edit/${record.projectId}`);
    },
    companyChange(value) {
      console.log(value);
      this.companyId = value;
    },
    //总经理选择需要下发的公司，做出决定，无论是自己的项目，还是组员通过组长一步一步提交上来的项目
    handleOk() {
      this.visible = false;
      this.submitProject(this.item, this.companyId);
    },
    // 判断用户权限
    submit(text, record) {
      console.log(record);
      this.item = record;
      /**
       * 如果是普通成员提交项目,就需要提交的时候将status变为2
       * 如果是组长提交项目,就需要在提交的时候将status变为3
       * 如果是总经理提交项目,就需要在提交项目的时候将status变为4并直接分配公司
       * 如果是管理员或者超级管理员,不能提交项目
       * 在这里我们为了方便，我们就可以封装一个专门提交请求的方法，因为不是都是立即提交的
       */
      if (this.roles[0] === "项目部普通成员") {
        this.status = 2;
        this.submitProject(record);
      } else if (this.roles[0] === "项目部分组组长") {
        this.status = 3;
        this.submitProject(record);
      } else if (
        this.roles[0] === "超级管理员" ||
        this.roles[0] === "项目部总经理"
      ) {
        this.status = 4;
        this.visible = true;
        //  开始选择公司选择之后才能提交
      }
    },
    submitProject(item, companyId = false) {
      let data;
      if (!companyId) {
        data = {
          projectId: item.projectId,
          status: this.status,
          amount: item.amount,
          term: item.term,
          rate: item.rate,
          guaranteeKind: item.guaranteeKind,
          guaranteeType: item.guaranteeType,
          insideBasic: item.insideBasic,
          insideLegal: item.insideLegal,
          insideCounter: item.insideCounter,
        };
        console.log(data, "普通的员工或者组长提交的项目");
      } else {
        data = {
          status: this.status,
          projectId: item.projectId,
          amount: item.amount,
          term: item.term,
          rate: item.rate,
          guaranteeKind: item.guaranteeKind,
          guaranteeType: item.guaranteeType,
          insideBasic: item.insideBasic,
          insideLegal: item.insideLegal,
          insideCounter: item.insideCounter,
          companyId,
        };
        console.log(data, "总经理要提交的数据");
      }
      this.$put("/project", data).then((res) => {
        if (res.data.code === "200") {
          this.$message.success("修改成功,请稍等，需要重新加载");
          this._getList();
        }
      });
    },

    // 分配公司
    selectCompany() {
      this.visible1 = false;
      this.hhhh(this.item, this.companyId);
    },

    hhhh(item, companyId) {
      console.log(companyId);
      console.log("分配公司的数据", item);
      if (companyId == undefined) {
        // 没有选择公司
        this.$message.success("请选择第三方公司后，重新提交");
      } else {
        this.agreeData.companyId = companyId;
        console.log(this.agreeData);
        // 分配完公司后修改数据库中的status（可以修改）
        this.$put("/project", this.agreeData).then((res) => {
          console.log("2222分配公司后修改成功");
        });
      }
    },
    // 点击同意按钮
    onCloseAgree() {
      console.log("点击了同意按钮");
      console.log("点击同意后获取的数据", this.agreeData);
      console.log(this.agreeInput);
      // 增加操作的备注
      this.agreeData.reviewNote = this.agreeInput;
      // 判断用户的角色 是管理员或者总经理就分配公司
      if (
        this.roles[0] == "项目部总经理" ||
        this.roles[0] == "超级管理员" ||
        this.roles[0] == "SRM管理员"
      ) {
        this.visible1 = true;
        this.isAgree = false;
      } else if (this.roles[0] == "项目部分组组长") {
        this.isAgree = false;
        console.log("组长同意提交的数据", this.agreeData);
        // 组长同意后修改数据库中的status（可以修改）
        this.$put("/project", this.agreeData).then((res) => {
          console.log("2222分配公司后修改成功");
        });
      }
    },
    // 点击同意获取的数据(projectId)
    agree(text, record) {
      console.log(
        "项目的id是",
        text.projectId,
        "状态是",
        text.status,
        "现在的用户是",
        this.roles[0]
      );
      // 判断提交的status值,可以由当前用户的角色来判断status
      if (this.roles[0] == "项目部分组组长") {
        console.log("现在的用户角色是", this.roles[0]);
        this.agreeData = {
          projectId: record.projectId,
          // 提交的status值,组长审核同意后status变为3
          status: text.status + 1, // 3
          // 显示Internal Server Error（500）应该是后台乱码
          reviewSuccess: 1,
        };
      } else if (
        this.roles[0] == "项目部总经理" ||
        this.roles[0] == "超级管理员" ||
        this.roles[0] == "SRM管理员"
      ) {
        console.log("现在的用户角色是", this.roles[0]);
        this.agreeData = {
          projectId: record.projectId,
          // 提交的status如果由总经理或者管理员来审核直接status = 4，并分配公司
          status: 4,
          reviewSuccess: 1,
        };
      } else if (this.roles[0] == "第三方公司") {
        //同意后status为91，审核完成；收到线下材料后status为92，出函
        console.log("现在的用户角色是", this.roles[0]);
      }
      this.isAgree = true;
      // 将项目信息获取到分配第三方公司功能中
      this.item = record;
      console.log("提交数据库的data的数据是", this.agreeData);
    },
    // 点击拒绝按钮====status需要变为-1
    refuse(record) {
      this.isRefuse = true;
      // console.log('我是拒绝的record',record)
      // record.reviewNote = this.refuseInput
      // console.log('数据中有没有reviewNote',record.reviewNote)
      this.refuseData = {
        projectId: record.projectId,
        status: -1, // 可以修改
        reviewSuccess: 0,
      };

      console.log("点击拒绝", this.refuseData);
    },
    refuseShowModal() {
      this.isRefuse = false;
      console.log(this.refuseInput);
      this.refuseData.reviewNote = this.refuseInput;
      console.log("拒绝要提交的数据是", this.refuseData);
      // 点击拒绝确认弹出框后修改数据库中的status（可以修改）
      this.$put("/project", this.refuseData).then((res) => {
        console.log("2222修改成功");
      });
    },
    confirm(e) {
      console.log(e);
      this.$message.success("Click on Yes");
    },
    cancel(e) {
      console.log(e);
      this.$message.error("Click on No");
    },
    getRole() {
      if (
        this.auser.roleName == "超级管理员" ||
        this.auser.roleName == "SRM管理员"
      ) {
        this.isShow1 = false;
        this.isShow2 = true;
      } else if (
        this.auser.roleName == "项目部总经理" ||
        this.auser.roleName == "项目部分组组长"
      ) {
        this.isShow1 = true;
        this.isShow2 = true;
      } else if (this.auser.roleName == "项目部普通成员") {
        this.isShow1 = true;
        this.isShow2 = false;
      }
    },
    getFalse() {
      this.isture = true;
    },
    getTrue() {
      this.isture = false;
      console.log("click", this.isture);
    },
    // 跳转新加项目页面
    toProjectAdd() {
      console.log("1111");
      this.$router.push({ path: "/project/add" });
    },
  },
  computed: {
    ...mapState({
      auser: (state) => state.account.user,
      roles: (state) => state.account.roles,
    }),
  },
};
</script>

<style scoped>
.all-project {
  width: 100%;
}

.all-project .ant-tabs {
  width: 100%;
}

.addProject {
  margin: 10px;
}
</style>
